/**
 * Copyright (c) 2012 Fujian FUNO Mobile Communication Technology Co., Ltd.
 * All rights reserved by FUNO.
 */
package com.funo.ehealth.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chinamobile.client1.Axis1Subscribe;
import com.chinamobile.client1.Axis1UnSubscribe;
import com.funo.ehealth.bean.Service;
import com.funo.ehealth.dao.UserOrderDao;
import com.funo.ehealth.util.LogUtil;
import com.funo.ehealth.util.StringUtil;

/** 
 * VGOPService
 * 
 * @version V1.1
 * @author zhangguangying
 * @date 2013-1-29
 */
public class VGOPService {
	
	/**
	 * VGOPService日志记录器
	 */
	private static final Log log = LogFactory.getLog(VGOPService.class);
	
	/**
	 * 发送订购请求到VGOP转发接口
	 * @param checkresult 
	 * 					包月订购指令和包月取消订购指令标识
	 * @param serviceCmd 
	 * 					上行指令
	 * @param serviceCode 
	 * 					业务代码
	 * @param srcterminalId 
	 * 					源号码
	 * @param destnationId 
	 * 					目的号码
	 * @param servicelistId 
	 * 					业务管理表Id
	 * @param subServType 
	 * 					业务类型子类编码
	 * @param costType 
	 * 					计费类型
	 * @return void
	 * @throws Exception 
	 */
	public int submitOrderToVGOP(Service service){
		int res = 0;
		
		try {
			//校验订购关系表中是否存在该用户的订购关系
			int userorderCount = UserOrderDao.queryUserOrderCountByUser(service.getUserTel(),service.getId(),1);
			if(userorderCount > 0){
				//如果订购表已经存在该用户的已经订购的记录，则发信息通知用户？
				LogUtil.warn(log, "无需重复订购！订购表已经存在该用户已经订购的记录，参数：{userTel:{},serviceListId:{}}", service.getUserTel(),service.getId());
				//删除订购关系临时表userorder_wait记录
				UserOrderDao.deleteUserorderWait(service.getOrderWaitId());
				return 1;
			}
			
			//订购关系生效时间
			String effTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			String msgtransationId_order = UserOrderDao.querySeqUserOrderId();
			
			res = addOrder(service.getServiceCode(),String.valueOf(service.getCostType()),service.getUserTel(),msgtransationId_order,service.getSubservtype(),effTime);
			
			if(res == 0){
				//将订购信息插入到数据库
				res = UserOrderDao.insertUserOrder(service.getUserTel(),String.valueOf(service.getId()),msgtransationId_order,effTime);
				//删除订购关系临时表userorder_wait记录
				UserOrderDao.deleteUserorderWait(service.getOrderWaitId());
			}else{
		    	//修改userorder_wait表的ISTOVGOP标识
				UserOrderDao.updateUserorderWaitByIstovgop(Integer.valueOf(res),service.getOrderWaitId());
			}
			
		} catch (Exception e) {
			// 订购关系同步异常处理
			LogUtil.error(log, e, "订购关系同步到VGOP异常：{}", ReflectionToStringBuilder.toString(service, ToStringStyle.SHORT_PREFIX_STYLE));
		}
		
		return res;
	}
	
	/**
	 * 发送订购请求到VGOP转发接口
	 * @param checkresult 
	 * 					包月订购指令和包月取消订购指令标识
	 * @param serviceCmd 
	 * 					上行指令
	 * @param serviceCode 
	 * 					业务代码
	 * @param srcterminalId 
	 * 					源号码
	 * @param destnationId 
	 * 					目的号码
	 * @param servicelistId 
	 * 					业务管理表Id
	 * @param subServType 
	 * 					业务类型子类编码
	 * @param costType 
	 * 					计费类型
	 * @return void
	 * @throws Exception 
	 */
	public int submitUnorderToVGOP(Service service){
		int res = 0;
		
		try {
			//校验订购关系表中是否存在该用户的订购关系
			int userorderCount = UserOrderDao.queryUserOrderCountByUser(service.getUserTel(),service.getId(),1);
			if(userorderCount <= 0){
				//如果订购表不存在该用户的已经订购的记录，则发信息通知用户？
				LogUtil.warn(log, "无需重复退订！订购表不存在该用户已经订购的记录，参数：{userTel:{},serviceListId:{}}", service.getUserTel(),service.getId());
				//删除订购关系临时表userorder_wait记录
				UserOrderDao.deleteUserorderWait(service.getOrderWaitId());
				return 1;
			}
			
			String expireTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());	//订购关系失效时间
			String msgtransationId_cancel = UserOrderDao.querySeqUserOrderId();
			
			String effTime = UserOrderDao.queryEffTime(String.valueOf(service.getId()),service.getUserTel());	//订购关系生效时间
			
			res = removeOrder(service.getServiceCode(),String.valueOf(service.getCostType()),service.getUserTel(),msgtransationId_cancel,service.getSubservtype(),effTime,expireTime);
			
			if(res == 0){
				//将订购记录为正在退订状态
				res = UserOrderDao.updateUserOrder(msgtransationId_cancel,expireTime,String.valueOf(service.getId()),service.getUserTel());
				//删除订购关系临时表userorder_wait记录
				UserOrderDao.deleteUserorderWait(service.getOrderWaitId());
			}else{
		    	//修改userorder_wait表的ISTOVGOP标识
				UserOrderDao.updateUserorderWaitByIstovgop(Integer.valueOf(res),service.getOrderWaitId());
			}
		} catch (Exception e) {
			//同步退订关系到VGOP异常处理
			LogUtil.error(log, e, "退订关系同步到VGOP异常：{}", ReflectionToStringBuilder.toString(service, ToStringStyle.SHORT_PREFIX_STYLE));
		}
		
		return res;
	}
	
	/**
	 * 业务订购接口
	 * @param destnationId 目的号码
	 * @param serviceCmd 订购指令
	 * @param serviceCode 业务代码
	 * @param costType 计费方式
	 * @param user_tel 用户号码
	 * @param transationId 订购的事务Id
	 * @param subServType 业务子编码
	 * @param effTime 生效时间
	 * @throws Exception 
	 */
	private int addOrder(String serviceCode,String costType,
			String user_tel , String transationId,
			String subServType,String effTime){
		String result = "7";	//本地执行错误
        String expireTime = "30000101000000";//formatter.format(new Date(d.getTime() + 24 * 60 * 60 * 1000));//订购关系失效时间
        String feeUser_ID=user_tel;   //计费用户标识，取值为不带“86”的手机号码
        String destUser_ID=user_tel;  //使用用户标识，取值为不带“86”的手机号码
        String servType = "";
        String feeType= costType; //计费类型，取值范围：0－免费、1－按条计费、2－包月计费、3－包时计费、4－包次计费
        
        if(subServType != null && subServType.trim().length() >= 6){
        	servType = subServType.substring(0,6);//业务类型编码
	    }
        
        try {
			result = new Axis1Subscribe().subscribe(effTime, effTime, expireTime, feeUser_ID, destUser_ID, "1", servType, subServType, "03", feeType, effTime ,transationId)+"";
		} catch (Exception e) {
			result = "-1";	//连接异常代码
			log.error(StringUtil.handleString("addOrder异常,参数：{oprTime:{},effTime:{},expireTime:{},feeUser_ID:{},destUser_ID:{},actionReasonID:{},servType:{},subServType:{},accessMode:{},feeType:{},timestamp:{},transactionID:{}}", effTime, effTime, expireTime, feeUser_ID, destUser_ID, "1", servType, subServType, "03", feeType, effTime ,transationId),e);
//			throw new UserOrderException(StringUtil.handleString("addOrder异常,参数：{oprTime:{},effTime:{},expireTime:{},feeUser_ID:{},destUser_ID:{},actionReasonID:{},servType:{},subServType:{},accessMode:{},feeType:{},timestamp:{},transactionID:{}}", effTime, effTime, expireTime, feeUser_ID, destUser_ID, "1", servType, subServType, "03", feeType, effTime ,transationId),e);
		}
		
        String logStr = StringUtil.handleString("VGOP订购反馈:{result:{},oprTime:{},effTime:{},expireTime:{},feeUser_ID:{},destUser_ID:{},actionReasonID:{},servType:{},subServType:{},accessMode:{},feeType:{},timestamp:{},transactionID:{}}", result, effTime, effTime, expireTime, feeUser_ID, destUser_ID, "1", servType, subServType, "03", feeType, effTime ,transationId);
//        log.info(logStr);
        
        //具体描述如下：0 ：成功 1 ：    用户数据无效 2 ：    数据库操作失败 3 ：	超过最大错误次数 4 ：	处理超时 5 ：	数据重复  6-99：	保留
        if("0".equals(result)){
        	String logtext = StringUtil.handleString("业务订购请求成功，用户：{}，业务代码：{}",user_tel,serviceCode);
			log.info(logtext+"，msgtransactionid_order："+transationId);
		}else if("-1".equals(result)){
			logStr = "业务订购请求失败，连接异常，用户：";
		}else if("1".equals(result)){
			logStr = "业务订购请求失败，用户数据无效，用户：";
		}else if("2".equals(result)){
			logStr = "业务订购请求失败，数据库操作失败，用户：";
		}else if("3".equals(result)){
			logStr = "业务订购请求失败，超过最大错误次数，用户：";
		}else if("4".equals(result)){
			logStr = "业务订购请求失败，处理超时，用户：";
		}else if("5".equals(result)){
			logStr = "业务订购请求失败，数据重复，用户：";
		}else{
			logStr = "业务订购请求失败，其他未定义的错误，用户：";
			result = "6";
		}
        
        String logtext = StringUtil.handleString("{}{}，业务代码：{}",logStr,user_tel,serviceCode);
        log.info(logtext+"，msgtransactionid_order："+transationId);
        
        return Integer.parseInt(result);
	}
	
	/**
	 * 业务订购取消接口
	 * @param destnationId 目的号码
	 * @param serviceCmd 订购指令
	 * @param serviceCode 业务代码
	 * @param costType 计费方式
	 * @param user_tel 用户号码
	 * @param transationId 订购的事务Id
	 * @param subServType 业务子编码
	 * @param effTime 生效时间
	 * @throws Exception 
	 */
	private int removeOrder(String serviceCode,String costType,
			String user_tel ,String transactionID,
			String subServType,String effTime,
			String expireTime){
		String result = "7";	//本地执行错误
	    String feeUser_ID=user_tel;   //计费用户标识，取值为不带“86”的手机号码
	    String destUser_ID=user_tel;  //使用用户标识，取值为不带“86”的手机号码
	    String servType = "";
	    String feeType= costType; //计费类型，取值范围：0－免费、1－按条计费、2－包月计费、3－包时计费、4－包次计费
	     
	    if(subServType != null && subServType.trim().length() >= 6){
	    	servType = subServType.substring(0,6);//业务类型编码
	    }
	    
        try {
			result = new Axis1UnSubscribe().unSubscribe(expireTime, effTime, expireTime, feeUser_ID, destUser_ID,"1", servType, subServType,"03", feeType,  expireTime,transactionID)+"";
		} catch (Exception e) {
			result = "-1";	//	连接异常代码
			log.error(StringUtil.handleString("removeOrder异常:{oprTime:{},effTime:{},expireTime:{},feeUser_ID:{},destUser_ID:{},actionReasonID:{},servType:{},subServType:{},accessMode:{},feeType:{},timestamp:{},transactionID:{}}", expireTime, effTime, expireTime, feeUser_ID, destUser_ID, "1", servType, subServType, "03", feeType,  expireTime, transactionID),e);
//			throw new UserOrderException(StringUtil.handleString("removeOrder异常:{oprTime:{},effTime:{},expireTime:{},feeUser_ID:{},destUser_ID:{},actionReasonID:{},servType:{},subServType:{},accessMode:{},feeType:{},timestamp:{},transactionID:{}}", expireTime, effTime, expireTime, feeUser_ID, destUser_ID, "1", servType, subServType, "03", feeType,  expireTime, transactionID),e);
		}
        String logStr = StringUtil.handleString("VGOP退订反馈:{result:{},oprTime:{},effTime:{},expireTime:{},feeUser_ID:{},destUser_ID:{},actionReasonID:{},servType:{},subServType:{},accessMode:{},feeType:{},timestamp:{},transactionID:{}}", result, expireTime, effTime, expireTime, feeUser_ID, destUser_ID, "1", servType, subServType, "03", feeType,  expireTime, transactionID);
        log.info(logStr);
        
        //具体描述如下：0 ：成功 1 ：    用户数据无效 2 ：    数据库操作失败 3 ：	超过最大错误次数 4 ：	处理超时 5 ：	数据重复  6-99：	保留
        if("0".equals(result)){
			String logtext = StringUtil.handleString("取消业务订购请求成功，用户：{}，业务代码：{}",user_tel,serviceCode);
			log.info(logtext+"，msgtransationId_cancel："+transactionID);
		}else if("-1".equals(result)){
			logStr = "取消业务订购请求失败，连接异常，用户：";
		}else if("1".equals(result)){
			logStr = "取消业务订购请求失败，用户数据无效，用户：";
		}else if("2".equals(result)){
			logStr = "取消业务订购请求失败，数据库操作失败，用户：";
		}else if("3".equals(result)){
			logStr = "取消业务订购请求失败，超过最大错误次数，用户：";
		}else if("4".equals(result)){
			logStr = "取消业务订购请求失败，处理超时，用户：";
		}else if("5".equals(result)){
			logStr = "取消业务订购请求失败，数据重复，用户：";
		}else{
			logStr = "取消业务订购请求失败，其他未定义的错误，用户：";
			result = "6";
		}
        
        String logtext = StringUtil.handleString("{}{}，业务代码：{}", logStr,user_tel,serviceCode);
		log.info(logtext+"，msgtransationId_cancel："+transactionID);
		
		return Integer.parseInt(result);
	}
	
}
